<script>
import { computed, defineComponent, reactive, ref } from 'vue'
import { libFileList } from '@Config/server/api'
import * as Antd from 'ant-design-vue'
import { cloneDeep, findIndex } from 'lodash'
export default defineComponent({
  emits: ['close', 'result'],
  props: {
    target: {
      //去除此项的路径显示
      type: Array,
      default: () => {
        return []
      },
    },
    isPublic: {
      type: Number,

      default: () => {
        return 0
      },
    },
  },
  setup(props, context) {
    let target = computed(() => {
      return cloneDeep(props.target)
    })

    let treeData = reactive({
      data: [
        {
          id: 0,
          name: '根目录',
          children: [],
          isLeaf: false,
        },
      ],
    })

    let loadDataHandler = async (node) => {
      let _r = await libFileList({
        id: node.dataRef.id,
        dataStatus: 0,
        fileType: 0,
        index: 1,
        size: 1000000,
        isPublic: props.isPublic,
      })

      node.dataRef.children = _r.data.records
        .map((x) => {
          return x
        })
        .filter((x) => {
          return findIndex(target.value, { id: x.id }) < 0
        })
      treeData.data = [...treeData.data]
    }

    let selectedData = ref()
    //选中某一项
    let selectHandler = (
      selectedKeys,
      { selected, selectedNodes, node, event }
    ) => {
      selectedData.value = selected ? { ...node.dataRef } : null
    }

    //取消
    let cancelHandler = () => {
      context.emit('close')
    }
    //提交
    let submitHandler = () => {
      context.emit('result', {
        tTarget: { ...selectedData.value },
        oTarget: [...target.value],
      })

      context.emit('close')
    }
    return {
      treeData,
      loadDataHandler,
      selectHandler,
      cancelHandler,
      selectedData,
      submitHandler,
    }
  },
  render() {
    return (
      <Antd.Row gutter={[20, 20]}>
        <Antd.Col span={24}>
          <Antd.Tree
            loadData={this.loadDataHandler}
            showLine={true}
            tree-data={this.treeData.data}
            replaceFields={{
              title: 'name',
              key: 'id',
              children: 'children',
            }}
            onSelect={this.selectHandler}
          />
        </Antd.Col>
        <Antd.Col span={24}>
          <Antd.Space>
            <Antd.Button
              type="primary"
              onClick={this.submitHandler}
              disabled={this.selectedData == null}
            >
              确定
            </Antd.Button>
            <Antd.Button type="primary" danger onClick={this.cancelHandler}>
              取消
            </Antd.Button>
          </Antd.Space>
        </Antd.Col>
      </Antd.Row>
    )
  },
})
</script>
